package com.cz.nongyetongv5.task;

import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.DaiShangChuanListAdapter;
import com.cz.nongyetongv5.bean.ChanPinJianCeRecord;
import com.cz.nongyetongv5.bean.DuChaXunChaRecord;
import com.cz.nongyetongv5.bean.JianDuJianChaRecord;
import com.cz.nongyetongv5.custom.TextProgressBar;
import com.cz.nongyetongv5.custom.TextProgressBar.ProgressListener;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.utils.HttpUtils;
import com.cz.nongyetongv5.utils.SerliazableUtil;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

/**
 * 待上传的后台任务
 *
 * @author Mr
 */
public class UploadDaiShangChuanTask extends
        AsyncTask<Integer, Integer, String> {

    private View root = null;

    private Context context = null;

    private String jsonData = null;

    private String authUserName = null;

    private String authPassword = null;

    private String requestUrl = null;

    /**
     * 请求返回的结果
     */

    /**
     * 按钮的菜单的布局
     */
    private ViewGroup llMenuLayout = null;

    /**
     * 进度条布局
     */
    private ViewGroup llProgressLayout = null;

    /**
     * 上传失败后的按钮
     */
    private Button btnBackUploadMenu = null;

    /**
     * 进度条
     */
    private TextProgressBar tpUploadProgress = null;

    /**
     * 这一项的数据
     */
    private Object itemData = null;

    // 数据的适配器
    private DaiShangChuanListAdapter adapter = null;

    /**
     * 返回的结果
     */
    private int responseCode;

    private String responseBody;


    CustomDialog progressDialog;

    /**
     * 判断请求是否返回数据
     */
    private boolean executeFinish = false;

    public UploadDaiShangChuanTask(View root, Context context, Object itemData,
                                   DaiShangChuanListAdapter adapter, String requestUrl,
                                   String jsonData, String authUserName, String authPassword, CustomDialog progressDialog) {

        this.root = root;
        this.context = context;

        this.itemData = itemData;

        this.adapter = adapter;

        this.requestUrl = requestUrl;
        this.jsonData = jsonData;
        this.authUserName = authUserName;
        this.authPassword = authPassword;
        this.progressDialog = progressDialog;

        llMenuLayout = (ViewGroup) root.findViewById(R.id.llMenuLayout);

        llProgressLayout = (ViewGroup) root.findViewById(R.id.llProgressLayout);

        btnBackUploadMenu = (Button) root.findViewById(R.id.btnBackUploadMenu);

        tpUploadProgress = (TextProgressBar) root
                .findViewById(R.id.tpUploadProgress);

        tpUploadProgress.setProgressListener(new ProgressListener() {

            @Override
            public void onExecuteFinish() {

                if (!executeFinish) {

                    tpUploadProgress.setText("服务器正在处理,请稍后..");

                }

            }
        });

    }

    /**
     * 在 doInBackground 之前
     */
    @Override
    protected void onPreExecute() {

        // 设置菜单为不显示
        llMenuLayout.setVisibility(View.GONE);
        // 设置进度条为显示
        llProgressLayout.setVisibility(View.VISIBLE);

        // 设置进度条为不显示
        btnBackUploadMenu.setVisibility(View.GONE);

        // 默认为百分之0
        tpUploadProgress.setProgress(0);
        tpUploadProgress.setText("0%");
    }

    /**
     * 在后台执行的逻辑
     */
    @Override
    protected String doInBackground(Integer... params) {

        Random random = new Random();
        /**
         * 获得开始的随机进度
         */
        int startProgress = random.nextInt(3);

        publishProgress(startProgress);

        // http 访问
        final HttpUtils httpUtil = HttpUtils.getInstance();

        httpUtil.setOnRequestExecuted(new OnRequestExecuted() {

            @Override
            public void onRequestExecuted(int responseCode, String responseBody) {

                tpUploadProgress.stopRandomProgress();

                UploadDaiShangChuanTask.this.responseBody = responseBody;

                UploadDaiShangChuanTask.this.responseCode = responseCode;

                try {
                    JSONObject jsonObject = new JSONObject(responseBody);

                    if (jsonObject.isNull("status")) {

                        UploadDaiShangChuanTask.this.responseCode = HttpUtils.UNKNOWERROR;

                    } else {

                        String state = jsonObject.getString("status");

                        if (!"success".equals(state) && !"true".equals(state)
                                && !"1".equals(state)) {

                            UploadDaiShangChuanTask.this.responseCode = HttpUtils.UNKNOWERROR;

                        }

                    }

                } catch (JSONException e) {

                    UploadDaiShangChuanTask.this.responseCode = HttpUtils.UNKNOWERROR;
                }

            }
        });

        httpUtil.sendRequest(requestUrl, jsonData, "POST", "UTF-8",
                authUserName, authPassword, null);

        int currentProgress = tpUploadProgress.getProgress();

        if (currentProgress >= 100) {
            tpUploadProgress.setText("服务器正在处理...");
        }

        return null;
    }

    // 当执行完成后
    @Override
    protected void onPostExecute(String result) {

        executeFinish = true;

        tpUploadProgress.setProgress(100);
        if (progressDialog != null) {
            progressDialog.dismiss();
        }

        if (responseCode != HttpUtils.SUCCESS) {

            btnBackUploadMenu.setVisibility(View.VISIBLE);

            // 当返回按钮点击的时候显示主菜单
            btnBackUploadMenu.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    v.setVisibility(View.GONE);

                    llMenuLayout.setVisibility(View.VISIBLE);

                    llProgressLayout.setVisibility(View.GONE);

                }
            });

        }

        switch (responseCode) {
            case HttpUtils.SUCCESS:

                tpUploadProgress
                        .setText(context.getString(R.string.upload_success));

                final String progressTxt = tpUploadProgress.getText();

			/*
             * Android 中的倒计时类,参数为(计时总数,几秒数一次) 这里是(3秒,1秒)
			 */
                try {
                    new CountDownTimer(3000, 1000) {

                        // 当数到的时候
                        @Override
                        public void onTick(long millisUntilFinished) {

                            // 剩余秒数
                            int second = (int) (millisUntilFinished / 1000);

                            tpUploadProgress.setText(progressTxt + "," + second
                                    + "秒后移除此项");

                        }

                        // 当执行完成的时候
                        @Override
                        public void onFinish() {

                            root.clearAnimation();

                            // 移除此项
                            Animation animation = AnimationUtils.loadAnimation(
                                    context, R.anim.bottom_window_anim_out_x);

                            animation.setDuration(150);

                            animation.setAnimationListener(new AnimationListener() {

                                @Override
                                public void onAnimationStart(Animation animation) {
                                }

                                @Override
                                public void onAnimationRepeat(Animation animation) {
                                }

                                @Override
                                public void onAnimationEnd(Animation animation) {

                                    // 设置菜单为显示
                                    llMenuLayout.setVisibility(View.VISIBLE);
                                    // 设置进度条为不显示
                                    llProgressLayout.setVisibility(View.GONE);

                                    // 设置进度条为不显示
                                    btnBackUploadMenu.setVisibility(View.GONE);

                                    // 默认为百分之0
                                    tpUploadProgress.setProgress(0);
                                    tpUploadProgress.setText("0%");

                                    adapter.remove(UploadDaiShangChuanTask.this.itemData);

                                    if (itemData instanceof JianDuJianChaRecord) {

                                        String id = ((JianDuJianChaRecord) itemData)
                                                .getFileId();

                                        SerliazableUtil.delete(id);

                                    } else if (itemData instanceof ChanPinJianCeRecord) {
                                        SerliazableUtil
                                                .deleteChanPinJianCe(((ChanPinJianCeRecord) itemData)
                                                        .getFileId());
                                    } else if (itemData instanceof DuChaXunChaRecord) {
                                        SerliazableUtil
                                                .deleteDuChaXunCha(((DuChaXunChaRecord) itemData)
                                                        .getFileId());
                                    }

                                }
                            });

                            root.setAnimation(animation);

                            animation.start();

                        }
                    }.start();

                } catch (Exception e) {
                }

                break;
            case HttpUtils.TIMEOUT:

                tpUploadProgress.setText(context.getResources().getString(
                        R.string.message_socktimeout));

                break;
            case HttpUtils.NETWORK_ERR:

                tpUploadProgress.setText(context.getResources().getString(
                        R.string.error_no_network));

                break;
            case HttpUtils.UNKNOWERROR:

                tpUploadProgress.setText(context.getResources().getString(
                        R.string.message_softerror));

                break;

        }

    }

    /**
     * 当进度更新的时候
     */
    @Override
    protected void onProgressUpdate(Integer... values) {

        int progress = values[0];

        tpUploadProgress.setProgress(progress);

        tpUploadProgress.startRandomProgress();

    }

}
